<template>
	<view class="header">
		<view class="img">
			<up-image
				:style="{ minHeight: '250px' }"
				src="/static/image/info/reportbg.png"
				mode="scaleToFill"
				width="100%" />
		</view>
		<view class="bg"></view>
		<view class="header-top">
			<view class="title-box" @click="showDevList">
				<view class="title">
					<text>
						{{ defaultDevice?.name || defaultDevice?.device_sn }}
					</text>
					<up-image
						:show-loading="true"
						src="/static/image/info/cut.png"
						width="12px"
						height="12px"></up-image>
				</view>
			</view>
			<view
				class="header-right"
				@click="
					navigateTo(
						`/pages/tabs/report/stats/index?device_sn=${defaultDevice?.device_sn}`
					)
				">
				<up-image
					:show-loading="true"
					src="/static/image/info/count.png"
					width="18px"
					height="18px"></up-image>
			</view>
		</view>
		<view class="header-content">
			<up-text
				:text="defaultDevice?.name || defaultDevice?.device_sn"
				size="18"
				class="top-text"></up-text>
			<up-text
				:text="`${t('report.device.sn')}：${defaultDevice?.device_sn}`"
				size="12"></up-text>
		</view>
	</view>
	<view class="scroll">
		<scroll-view
			scroll-y
			:scroll-into-view="'list-' + selTimezone"
			class="scroll-box">
			<view class="tab">
				<up-text
					:text="`${t('report.totalAll')}${query.total}${t(
						'report.totalUnit'
					)}`"
					size="14"
					color="#333"
					@scrolltolower="getReportList()"
					bold></up-text>
			</view>
			<up-list class="cell-list" v-if="reportList.length && !isLoading">
				<up-list-item
					v-for="(item, index) in reportList"
					:key="`item-${index}`">
					<up-cell @click="goDetail(item)">
						<template #icon>
							<view class="img-box">
								<up-avatar
									shape="square"
									size="48"
									src="/static/image/info/listIcon.png"
									customStyle="margin: -3px 5px -3px 0"></up-avatar>
							</view>
						</template>
						<template #title>
							<view class="tilte-box">
								<view class="top-box">
									<view class="title">
										<text>
											{{
												item.plan_name ||
												t("report.plan.name")
											}}
										</text>
										<up-tag
											text="jt_0625"
											size="mini"></up-tag>
									</view>
									<text class="time">
										{{
											item.clean_record.start_time_pretty
												.slice(5, 10)
												.replace(/-/g, "/")
												.replace(/\//g, "-")
										}}
									</text>
								</view>
								<view class="bottom-text">
									<text>
										{{ t("report.plan.area") }}：{{
											format(item.clean_record.area)
										}}m²
									</text>
									<text class="right">
										{{ t("report.plan.time") }}：{{
											formatTime(
												item.clean_record.cleaning_time
											)
										}}m²
									</text>
								</view>
							</view>
						</template>
					</up-cell>
				</up-list-item>
			</up-list>
			<view class="loading" v-show="isLoading">
				<LoadingDots />
			</view>
			<view class="no-more" v-if="reportList.length && isLoadMore">
				{{ t("noMore") }}
			</view>
			<up-empty
				v-if="!reportList.length && !isLoading"
				icon="/static/image/common/noData.svg"
				width="35%"
				textSize="18"
				text-color="#b8b8b8"
				safeAreaInsetBottom
				:text="t('noList')"></up-empty>
		</scroll-view>
	</view>
	<CheckDevPop
		v-if="showPop"
		:defaultDevice="defaultDevice"
		:deviceList="deviceList"
		@changeDev="changeDev"
		@closePop="closePopFun" />
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, reactive, onUnmounted } from "vue";
import {
	getBoundVcus,
	getRecordPlans,
	getDeviceMapsApi,
} from "@/service/index";
import LoadingDots from "@/components/LoadingDots/index.vue";
import { useReportDetailStore } from "@/stores/index";
import CheckDevPop from "./components/checkDevPop.vue";
import { onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import type * as type from "./type";
import { useI18n } from "vue-i18n";

// 国际化
const { locale, t } = useI18n();
const instance: any = getCurrentInstance();
const selTimezone = ref<number>(0);
const reportList = ref<type.reportItem[]>([]);
const deviceList = ref<type.DeviceItem[]>([]);
const defaultDevice = ref<type.DeviceItem | null>(null);
const tokenStore = useUniversalStorage("token", "");
const isLoading = ref(false);
const isLoadMore = ref(false);
const showPop = ref(false);
const query = reactive({
	page: 1,
	size: 10,
	total: "push",
});
const detailStore = useReportDetailStore();
const format = (num: number | string): string => {
	const parsed = Number(num);
	return isNaN(parsed) ? "0.00" : parsed.toFixed(2);
};
const formatTime = (seconds?: number): string => {
	if (!seconds) return "";
	const minutes = (seconds / 60).toFixed(0);
	const second = (seconds % 60).toFixed(0);
	return `${minutes}${t("recordDetails.minute")}${second}${t(
		"recordDetails.sec"
	)}`;
};
const navigateTo = (url: string) => {
	uni.navigateTo({
		url: url,
	});
};
const getReportList = async () => {
	try {
		isLoading.value = true;
		const { data } = (await getRecordPlans({
			device_sn: defaultDevice.value?.device_sn,
			page: query.page,
			size: query.size,
		})) as type.RecordResponse;

		if (data?.code === 0) {
			query.total = data.data.total;
			if (data.data.historys.length > 0) {
				if (query.page === 1) {
					reportList.value = data.data.historys;
				} else {
					reportList.value = [
						...reportList.value,
						...data.data.historys,
					];
				}
				query.page += 1;
			} else {
				if (query.page === 1) {
					reportList.value = [];
				}
				isLoadMore.value = true;
			}
		} else {
			instance.proxy.$message(
				data?.msg || t("request.failed"),
				"warning"
			);
		}
	} catch (error) {
		instance.proxy.$message("网络请求异常", "error");
	} finally {
		isLoading.value = false;
	}
};
const getBindDevList = async () => {
	try {
		const { data } = await getBoundVcus({});
		if (data?.code === 0) {
			deviceList.value = data.data.devices;
			defaultDevice.value = deviceList.value[0] || null;
			if (defaultDevice.value?.device_sn) {
				await getDeviceMapsApi({
					device_sn: defaultDevice.value?.device_sn || "",
				});
				getReportList();
			}
		} else {
			if (tokenStore.value) {
				instance?.proxy?.$message(
					data?.msg || "获取设备失败",
					"warning"
				);
			}
		}
	} catch (error) {
		instance?.proxy?.$message("网络请求异常", "error");
	}
};
const closePopFun = () => {
	showPop.value = false;
};
const showDevList = () => {
	showPop.value = true;
};
const changeDev = (device: type.DeviceItem) => {
	defaultDevice.value = device;
	isLoadMore.value = false;
	query.page = 1;
	reportList.value = [];
	getReportList();
	showPop.value = false;
};
const goDetail = (item: type.DeviceItem) => {
	detailStore.reportDetailData = item;
	detailStore.setReportDetail(item);
	uni.navigateTo({
		url: "/pages/tabs/report/detail/index?type=1",
	});
};
// 上拉加载更多
onReachBottom(async () => {
	console.log("触底加载");
	console.log(isLoadMore.value);
	if (isLoadMore.value || isLoading.value) return;
	try {
		await getReportList();
	} finally {
		isLoading.value = false;
	}
});
const topHeight = ref("0");
onMounted(() => {
	// 获取状态栏高度
	// #ifdef APP-PLUS
	const statusBarHeight = ref(0);
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight || 0;
	topHeight.value = statusBarHeight.value + "px";
	// #endif
	getBindDevList();
});
onUnmounted(() => {});
//下拉刷新
onPullDownRefresh(() => {
	setTimeout(() => {
		query.page = 1;
		reportList.value = [];
		getBindDevList();
		uni.stopPullDownRefresh();
	}, 1500);
});
</script>

<style lang="scss" scoped>
body {
	background-color: #fff;
}
.header {
	width: 100%;
	height: 250rpx;
	position: fixed;
	top: v-bind(topHeight);
	left: 0;
	z-index: 99;
	overflow: hidden;
	.img {
		width: 100%;
		z-index: -1;
		margin: 0;
		position: absolute;
	}
	.bg {
		position: absolute;
		width: 100%;
		height: 250rpx;
		background: #000;
		opacity: 0.3;
		z-index: -2;
	}
	.header-top {
		z-index: 2;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-left: 10%;
		box-sizing: border-box;
		height: 50px;
		.title-box {
			flex: 1;
			text-align: center;
		}
		.title {
			display: inline-block;
			background: #000000;
			border-radius: 27px;
			color: #fff;
			padding: 5px 10px;
			cursor: pointer;
			padding-bottom: 0;
			height: 27px;
			margin: 0 auto;
		}
		.header-right {
			width: 10%;
		}
		:deep(.u-transition) {
			margin-left: 5px;
			display: inline-block !important;
		}
	}
	.header-content {
		padding: 0 30rpx;
		:deep(.u-text__value) {
			color: #fff !important;
		}
		.top-text {
			padding-bottom: 10rpx;
		}
	}
}

.scroll {
	padding-top: 258rpx;
	width: 100%;
	z-index: -1;
	height: 100vh;
	background-color: #fff;
	// #ifdef APP-PLUS
	padding-top: calc(258rpx + v-bind(topHeight));
	// #endif
}
.scroll-box {
	// height: calc(100vh - 129px - v-bind(topHeight));
}
.tab {
	padding: 4px 22px;
	border-bottom: 1px solid #f5f6f7;
}
.cell-list {
	:deep(.u-cell__body) {
		padding: 15px 15px 10px 15px !important;
	}
	:deep(.u-line) {
		border-bottom: 1px solid #f5f6f7 !important;
	}
	.img-box {
		background-color: #ecf2fe;
		width: 48px;
		height: 48px;
		margin: 5px 5px 13px 0px;
		border-radius: 8px;
	}
	.tilte-box {
		display: flex;
		flex-direction: column;
		padding: 0 0 12px 10px;
		.top-box {
			margin-top: 5px;
			display: flex;
			justify-content: space-between;
			:deep(.u-tag--primary) {
				background-color: #f5f6f7;
				margin-left: 5px;
				line-height: 23px;
				border: 0;
			}
			:deep(.u-tag__text--primary) {
				color: #aaabae;
			}
			.title {
				color: rgba(0, 0, 0, 0.9);
				font-size: 16px;
				max-width: calc(100% - 100px);
				margin-bottom: 8px;
			}
			.time {
				font-size: 12px;
				cursor: pointer;
				color: #97989a;
			}
		}
		.bottom-text {
			color: #97989a;
			font-size: 12px;
			.right {
				margin-left: 20rpx;
			}
		}
	}
}
.loading {
	height: 100vh;
	background-color: #d8d8d8;
}
.no-more {
	width: 100%;
	height: 25px;
	line-height: 25px;
	text-align: center;
	color: #999;
	font-size: 14px;
}
</style>
